<template>
    <div class="">
        <div class="float_left tree_box">
            <h4 class="margin_bottom20" style="float:left">组织机构</h4>
             <el-row type="flex" class="row-bg" justify="space-between">
              <el-col :span="24">
                <el-button type="danger" style="float:right" size="small" 
                    @click="deleteDept(selectedDeptId, selectedIsActive)" 
                    :disabled="this.selectedDeptId == ''"
                    v-show="this.selectedIsActive == 1">停用此机构</el-button>
                <el-button type="danger" style="float:right" size="small" 
                    @click="recoverDept(selectedDeptId, selectedIsActive)" 
                    :disabled="this.selectedDeptId == ''"
                    v-show="this.selectedIsActive == 0">重新启用</el-button>
              </el-col>
             </el-row>
            <div style="clear:both"></div>

            <el-input placeholder="输入关键字进行过滤" v-model="filterText">
            </el-input>

            <el-tree :data="treeJson"
                    node-key="id"
                    :default-expanded-keys="['1']"
                    current-node-key = "1"
                    :props="defaultProps"
                    :render-content="renderContent"
                    :expand-on-click-node=true
                    highlight-current
                    @current-change="currentChange" 
                    :filter-node-method="filterNode"
                    ref="tree"
                    >
            </el-tree>
        </div>
        <div class="operate_main">
            <h4 class="margin_bottom20">人员列表</h4>
            <el-row type="flex" class="row-bg" justify="space-between">
              <el-col :span="16">
                <!--<el-button-group>-->

                <el-button type="primary" size="small" @click="addUser"
                    :disabled="this.selectedIsActive == 0"><i class="iconfont icon-plus"></i>新增</el-button>
                <el-button type="primary" size="small" @click="editUser" icon="edit"
                    :disabled="this.selectedIsActive == 0">编辑</el-button>
                <el-button type="primary" size="small" @click="deleteUser" icon="delete"
                    :disabled="this.selectedIsActive == 0">删除</el-button>

              <!--</el-button-group>-->
              </el-col>
              <el-col :span="8">
                <el-input placeholder="姓名..." size="small" v-model="searchKey">
                    <el-button slot="append" icon="search" @click="search" :disabled="this.selectedIsActive == 0"></el-button>
                </el-input>
              </el-col>
            </el-row>
            <template>
                <el-table :data="tableData" border style="width: 100%; text-align: center;margin-top:10px;" @selection-change="handleSelectionChange" v-loading.body="loading">
                    <el-table-column header-align="center" type="selection"></el-table-column>
                    <el-table-column header-align="center" prop="accountName" label="帐号"></el-table-column>
                    <el-table-column header-align="center" prop="realName" label="真实姓名"></el-table-column>
                    <!-- <el-table-column header-align="center" prop="createTime" label="创建时间"></el-table-column> -->
                    <!-- <el-table-column header-align="center" prop="lastLoginTime" label="最后登录时间"></el-table-column> -->
                    <el-table-column header-align="center" label="操作" width="120">
                        <template slot-scope="scope">
                            <el-button
                            @click="changeDeptEmp(tableData[scope.$index].id)"
                            size="small">
                            调动
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage"
                    :page-sizes="[20,50,100,200]"
                    :page-size="limit"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
                </el-pagination>
            </template>
        </div>

        <!-- 表单弹窗 -->
        <el-dialog title="添加部门" v-model="dialogFormVisible" :show-close="false">
            <el-form :model="dept" ref="deptForm">
                <el-form-item label="部门名称" :label-width="formLabelWidth" prop="name"
                    :rules="[{ required: true, message: '名称不能为空'}]">
                    <el-input v-model="dept.name" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="部门编号" :label-width="formLabelWidth" prop="deptNo" :rules="[{ required: true, message: '编号不能为空'}]">
                    <el-input v-model="dept.deptNo" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="显示顺序" :label-width="formLabelWidth" prop="displayOrder" :rules="[{ required: true, message: '编号不能为空'}]">
                    <el-input-number v-model="dept.displayOrder" :min="0"></el-input-number>
                </el-form-item>
                <el-form-item label="上级部门" :label-width="formLabelWidth">
                    {{dept.parentDeptName}}
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="reset('deptForm')">取 消</el-button>
                <el-button type="primary" @click="submit('deptForm')">确 定</el-button>
            </div>
        </el-dialog>

                <!-- 表单弹窗 -->
        <el-dialog title="添加人员" v-model="dialogUserVisible" :show-close="false">
            <el-form :model="user" ref="userForm">
                <el-form-item label="所属部门" :label-width="formLabelWidth">
                    {{user.deptName == null ? selectedDeptName : user.deptName}}
                </el-form-item>
                <el-form-item label="帐号" :label-width="formLabelWidth" prop="accountName" 
                    :rules="[{ required: true, message: '帐号不能为空'}]">
                    <el-input v-model="user.accountName" :disabled="user.accountName != ''" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="密码" :label-width="formLabelWidth" prop="accountPwd" 
                    :rules="[{ required: true, message: '密码不能为空'}]">
                    <el-input type="password" v-model="user.accountPwd" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="真实姓名" :label-width="formLabelWidth" prop="realName"
                    :rules="[{ required: true, message: '真实姓名不能为空'}]">
                    <el-input v-model="user.realName" auto-complete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="resetUserForm('userForm')">取 消</el-button>
                <el-button type="primary" @click="submitUserForm('userForm')">确 定</el-button>
            </div>
        </el-dialog>

        <el-dialog title="选择调动的部门" v-model="dialogChangVisible" :show-close="false">
            <el-tree :data="treeJson"
                    node-key="id"
                    :default-expanded-keys="['1']"
                    current-node-key = "1"
                    :props="defaultProps"
                    :expand-on-click-node=true
                    highlight-current
                    @current-change="currentSelect" 
                    >
            </el-tree>
            <div slot="footer" class="dialog-footer">
                <el-button @click="resetChangeDeptForm('changeDept')">取 消</el-button>
                <el-button type="primary" @click="submitChangeDeptForm('changeDept')">确 定</el-button>
            </div>
        </el-dialog>

        <div class="clear"></div>

    </div>
</template>
    <style>
        .messageDIY {
            top: 40%;
        }
        /*控制数出现滚动条*/
        /*.el-tree-node{
            width:500px;
        }
        .el-tree{
            overflow-x: scroll;
        }*/
        .tree_edit_diy{
            float: right;
             margin-right: 20px; 
             /*display:none*/
        }
        /*控制添加按钮的显示隐藏*/
        /*.el-tree-node__content:hover .tree_edit_diy{
            display: inline-block
        }*/
    </style>
<script>

    export default {
        name:'app',
        data() {
            return {
                filterText: '',
                treeJson: [],
                defaultProps: {
                    children: 'children',
                    label: 'label'
                },
                tableData: [],
                dialogFormVisible: false,
                dialogUserVisible: false,
                dialogChangVisible: false,
                dept: {
                    id:'',
                    name: '',
                    deptNo: '',
                    parentDeptId: '',
                    parentDeptName: '',
                    displayOrder: 0,
                    isActive: 1
                }, 
                userInit: '',
                user: {
                    id: '',
                    accountName: '',
                    accountPwd:'',
                    realName: ''
                },
                formLabelWidth: '120px',
                currentPage: 1,
                total: 0,
                limit: 20,
                selectedIsActive: 1,
                selectedDeptId: 1,
                selectedDeptName: '本部',
                searchKey: '',
                selectedUserId: '',
                selectedNewDeptId: '',
                selectedUsers: [],
                loading: false
            }
        },
    methods: {
        append(store, data) {
            if (data.isActive == 1) {
                this.dialogFormVisible = true;
                this.dept.parentDeptId = data.id;
                this.dept.parentDeptName = data.label;
            } else {
                this.$message({
                    type: 'info',
                    message: '已停用，不能操作！'
                });
            }
        },

        deleteDept(id, isActive) {
            if (isActive == 1) {
                    this.$confirm('确认停用此组织?停用之前，需要把该组织下所有人员移除。', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    console.log(this.tableData);
                    if(this.tableData.length > 0) {
                        this.$message({
                            type: 'error',
                            message: '停用之前，需要把该组织下所有人员移除'
                        });
                        return;
                    }
                    this.$http.delete(API.depts + "/" + id).then((response) => {
                        // console.log(response.body.data);
                        if(response.body.status == 0) {
                            this.$message({
                                type: 'info',
                                message: '停用成功'
                            });
                            this.$http.get(API.deptTree, {params: {userId: localStorage.userId}}).then((response) => {
                                this.treeJson = response.body.data;
                                this.loadData();
                            });
                        } else {
                            this.$message({
                                type: 'error',
                                message: response.body.msg
                            });
                        }
                    });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消'
                    });
                }); 
            } else {
                this.$message({
                    type: 'info',
                    message: '已停用，不能操作！'
                });
            }
        },

        recoverDept(id, isActive) {
            if (isActive == 0) {
                  this.$confirm('确定重新启用该部门？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$http.put(API.depts + "/" + id).then((response) => {
                        // console.log(response.body.data);
                        if(response.body.status == 0) {
                            this.$message({
                                type: 'info',
                                message: '操作成功'
                            });
                            this.$http.get(API.deptTree, {params: {userId: localStorage.userId}}).then((response) => {
                                this.treeJson = response.body.data;
                                this.loadData();
                            });
                        } else {
                            this.$message({
                                type: 'error',
                                message: response.body.msg
                            });
                        }
                    });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消'
                    });
                }); 
            } else {
                this.$message({
                    type: 'info',
                    message: '未停用，不能操作！'
                });
            }
        },

        edit(store, data) {
            //如果是本部，根级部门
            // if(data.id == 1) {
            //     this.dialogFormVisible = true;
            //     this.dept.name = data.label;
            //     this.dept.parentDeptId = 0;
            //     this.dept.parentDeptName = "无";
            //     this.dept.displayOrder = data.displayOrder;
            // } else {
                if (data.isActive == 1) {
                    this.$http.get(API.depts + "/" + data.id, {params:{}}).then((response) => {
                    // console.log(response.body.data);
                        this.dialogFormVisible = true;
                        var department = response.body.data;
                    
                        this.dept = department;
                        if (data.id == 1) {
                            this.dept.parentDeptId = 0;
                            // this.dept.name = data.label;
                            this.dept.parentDeptName = "无";
                        }
                    }, (response) => {
                        // error callback
                    }); 
                } else {
                this.$message({
                    type: 'info',
                    message: '已停用，不能操作！'
                });
            }
        },

        renderContent(h, { node, data, store }) {
            
            return (
            <span>
                <span>{data.isActive == 1 ? node.label : (node.label + '(已停用)')}</span>
                <span class="tree_edit_diy" >
                    <el-button size="mini"  on-click={ () => this.append(store, data) }>添加下级</el-button>
                    <el-button size="mini"  on-click={ () => this.edit(store, data) }>编辑</el-button>
                </span>
            </span>);
        },

        submit(deptForm) {
            this.$refs[deptForm].validate((valid) => {
                if (valid) {
                    this.$http.post(API.depts, this.dept, {params:{userId: localStorage.userId  }}).then((response) => {

                        //返回值是0的时候表示成功
                        if(response.body.status == 0) {
                            this.treeJson = response.body.data;
                            this.dialogFormVisible = false;
                            this.$refs[deptForm].resetFields();
                        }
                    }, (response) => {
                        // error callback
                    });
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },

        reset(deptForm) {
            this.dialogFormVisible = false;
            this.$refs[deptForm].resetFields();
        },

        //部门树的点击事件，给selectedDept赋值
        currentChange(data, node, store) {
            // console.log(data);
            this.selectedDeptId = data.id;
            this.selectedDeptName = data.label;
            this.selectedIsActive = data.isActive;

            if (data.isActive == 1) {
                this.loadData(data.id);
            } else {
                this.tableData = null;
                this.total = 0;
            }
            // console.log("选择的部门树id：" + this.selectedDeptId); 
        },
        currentSelect(data) {
            this.selectedNewDeptId = data.id;
        },

        //pageSize 改变时会触发,就是limit改变时候触发
        handleSizeChange() {
            
        },

        //currentPage 改变时会触发
        handleCurrentChange(currentPage) {
            // console.log(currentPage);
            this.currentPage = currentPage;
            this.loadData(this.selectedDeptId);
        },

        loadData(deptId) {
            this.loading = true;
            this.$http.get(API.users, {params:{offset: this.limit*(this.currentPage - 1), limit: this.limit, deptId: deptId, searchKey: this.searchKey}}).then((response) => {

                this.tableData = response.body.data.rows;
                this.total = response.body.data.total;
                console.log("调动成功加载也成功");  
                this.loading = false;  
            }, (response) => {
                // error callback
            }); 
        },

        //增加用户
        addUser() {
            this.dialogUserVisible = true;

            //添加的时候把数据初始化
            this.user = this.userInit;
        },

        // //table中选中一行得到的数据
        // currentSelectUser(currentRow) {

        //     if(currentRow != null) {
        //         this.selectedUserId = currentRow.id;
        //         this.user = JSON.parse(JSON.stringify(currentRow));
        //     }
        // },

        handleSelectionChange(val) {
            this.selectedUsers = val;
            console.log(this.selectedUsers);
        },

        //编辑用户
        editUser() {
            if(this.selectedUsers.length > 1) {
                this.$message({
                    message: '只能选择一条数据进行编辑',
                    type: 'warning',
                    customClass: 'messageDIY'
                });

                return;
            } else if(this.selectedUsers.length != 0){
                this.dialogUserVisible = true;
                this.user = JSON.parse(JSON.stringify(this.selectedUsers[0]));
            }
        },

        //删除用户
        deleteUser() {
            if(this.selectedUsers.length < 1) {
                this.$message({
                    message: '请选择要删除的数据',
                    type: 'warning'
                });
                return;
            }

            this.$confirm('删除后帐号不可恢复，确定删除?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                var userIds = new Array();
                for (var i = 0; i < this.selectedUsers.length; i++) {
                    let user = this.selectedUsers[i];
                    userIds.push(user.id);
                }
                this.$http.delete(API.users, {params:{userIds: userIds.join(",")}}).then((response) => {

                    //返回值是0的时候表示成功,重新加载数据
                    if(response.body.status == 0) {
                        this.loadData(this.selectedDeptId);
                    }
                }, (response) => {
                    // error callback
                }); 
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },

        //提交user表单
        submitUserForm(userForm) {
            this.$refs[userForm].validate((valid) => {
                if (valid) {
                    this.$http.post(API.users, this.user, {params:{deptId: this.selectedDeptId}}).then((response) => {
                        //返回值是0的时候表示成功,关闭窗口，重新加载数据
                        if(response.body.status == 0) {
                            this.$refs[userForm].resetFields();
                            this.user = this.userInit;
                            this.dialogUserVisible = false;
                            this.loadData(this.selectedDeptId);
                        }
                    }, (response) => {
                        // error callback
                    });
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },

        //取消user表单
        resetUserForm(userForm) {
            this.$refs[userForm].resetFields();
            this.user = this.userInit;
            this.dialogUserVisible = false;
        },

        search() {
            this.loadData(this.selectedDeptId);
        },

        changeDeptEmp(userId) {
            // console.log("需要调动的人员id" + userId);
            this.selectedUserId = userId;
            this.dialogChangVisible = true;
        },

        //保存人员部门调动的
        submitChangeDeptForm() {
            this.$http.post(API.changeDeptEmp, {}, {params:{userId: this.selectedUserId, deptId: this.selectedNewDeptId}}).then((response) => {

                //返回值是0的时候表示成功
                if(response.body.status == 0) {
                    //隐藏掉窗口，并重新加载一下数据
                    this.dialogChangVisible = false;
                    this.loadData(this.selectedDeptId);
                }
            }, (response) => {
                // error callback
            });            
        },

        //关闭人员调动的页面
        resetChangeDeptForm() {
            this.dialogChangVisible = false;
        },
        filterNode(value, data) {
            if (!value) return true;
            return data.label.indexOf(value) !== -1;
      }
    },

    created() {
        this.userInit = this.user;
        //获取完树的数据之后，默认查询根节点的人员数据
        this.$http.get(API.deptTree, {params: {userId: localStorage.userId}}).then((response) => {
            this.treeJson = response.body.data;
            this.loadData();
        }, (response) => {
            // error callback
        }); 
    },

    watch: {
      filterText(val) {
        this.$refs.tree.filter(val);
      }
    },
};
</script>

